<template>
  <div class="add_audition">
    <div class="common_bg"></div>
    
    <div class="container">
      <div class="card">
        <div class="base_form">
          <ul class="form_list" >
            <li @click="clcikShowBottomArea('school')">
              <van-cell :value="formData.schoolName"  is-link>
                <template slot="title">
                  <span class="custom-title">校区</span>
                </template>
              </van-cell>
            </li>
            <li @click="clcikShowRightArea('product')">
              <van-cell :value="formData.productName" is-link>
                <template slot="title">
                  <span class="custom-title">课程</span>
                </template>
              </van-cell>
            </li>
            <li @click="clcikShowBottomArea('date', 'startDate')">
              <van-cell :value="formData.classStartTime" is-link>
                <template slot="title">
                  <span class="custom-title">开始时间</span>
                </template>
              </van-cell>
            </li>
            <li @click="clcikShowBottomArea('date', 'endDate')">
              <van-cell :value="formData.classEndTime" is-link>
                <template slot="title">
                  <span class="custom-title">结束时间</span>
                </template>
              </van-cell>
            </li>
            <li @click="clcikShowBottomArea('classRoom')">
              <van-cell :value="formData.classRoomName" is-link>
                <template slot="title">
                  <span class="custom-title">教室</span>
                </template>
              </van-cell>
            </li>
            <li @click="clcikShowBottomArea('teacher')" >
              <van-cell :value="formData.employeesName" is-link>
                <template slot="title">
                  <span class="custom-title">教师</span>
                </template>
              </van-cell>
            </li>
            
            <li><van-field v-model="formData.accommodateStudent" label="容纳学员" placeholder="请输入" /></li>
            
            <li v-if="type == 'update'" @click="clcikShowRightArea('arrangeStudentList')">
              <van-cell :value="formData.arrangeStudentArr" is-link>
                <template slot="title">
                  <span class="custom-title">安排学员</span>
                </template>
              </van-cell>
            </li>

            <li class="checkBox">
              <van-collapse v-model="activeNames" title="标题1" name="1">
                <van-collapse-item :title="computedTitle" name="1">
                  <van-checkbox-group v-model="checkedList">
                    <ul class="check_list">
                      <li v-for="(item, index) in studentList" :class="{'activeItem': checkedList.indexOf(item) > -1 || checkedList.indexOf(item.studentId) > -1} "  :key="index">
                        <van-checkbox  :name="computedCheckStudent(item)">{{item.studentName}}</van-checkbox>
                        <span class="salePerson" >顾问 {{item.personName || '无'}}</span>
                      </li>
                    </ul>
                    <div class="signIn_box" v-if="$route.params.type == 'update'">
                      <span class="checked_num">已选中{{checkedList.length}}项</span>
                      <span class="btn_signIn" @click="updateCheckStatus">确认签到</span>
                    </div>
                  </van-checkbox-group>
                </van-collapse-item>

                
              </van-collapse>
            </li>

            
          </ul>
        </div>
      </div>

      
    </div>

    <div class="icon_place" v-if="type=='add'" @click="save"></div>
    <div class="icon_place" v-else @click="update"></div>

    <div class="popup">
      <van-popup v-model="showBottomArea" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-if="bottomType == 'date'"
          v-model="currentDate"
          :formatter='formatter'
          title=""
          type="datetime"
          :min-date="minDate"
          @cancel="onCancel"
          @confirm="onConfirm"
        />

        <van-picker
          show-toolbar
          v-else
          title=""
          value-key="label"
          :columns="bottomAreaList"
          @cancel="onCancel"
          @confirm="onConfirm"
        />
      </van-popup>
    </div>

    <div class="popup_search_child">
      <van-popup v-model="showSearchChildren" class="screen_box" position="right" :style="{ height: '85%' }">
        <div class="screen_title_box">
          <i class="icon_return" @click="showSearchChildren = false;"></i>
          <span class="screen_title">{{searchChildrenTitle}}</span>
          <span class="btn_confirm" @click="confirmChildPop">确定</span>
        </div>

        <div class="search_list">
          <van-checkbox-group v-model="checkedRightList">
            <van-cell-group>
              <van-cell
                v-for="(item, index) in rightPopupList"
                clickable
                :key="item.id"
                :title="item.label"
                @click="toggle(index)"
              >
                <van-checkbox
                  :name="item.id"
                  ref="checkboxes"
                  slot="right-icon"
                />
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>
      </van-popup>
    </div>




  </div>
</template>

<style>

.add_audition .van-hairline--top-bottom::after {
  border: none !important;

}

.add_audition .checkBox .van-cell:not(:last-child)::after {
  border-bottom: none;
}
.add_audition .van-field__control {
  text-align: right;
}
.add_audition .van-collapse-item__title .van-cell__right-icon::before {
  transform: rotate(0deg);
}
.add_audition .van-collapse-item__title--expanded .van-cell__right-icon::before{
  transform: rotate(90deg);
}


.add_audition .van-checkbox {
  position: relative;
}
.add_audition .van-checkbox__icon {
  height: auto;
}
.add_audition .van-checkbox__icon--checked .van-icon{
    background-color: #FF9853;
    border-color: #FF9853;
}
.add_audition .checkBox .van-checkbox__icon .van-icon {
  width: 1.333333rem;
  height: 1.333333rem;
  border: 1px dashed #FF9853;
}
.add_audition .van-checkbox__label {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 100%;
  font-size: .373333rem;
  color: #FF9853;
  transform: translate(-50%, -50%);
  margin-left: 0;
  text-align: center;
}
/* .add_audition .van-checkbox__icon--checked .van-checkbox__label {
  color: #fff !important;
} */
.add_audition .checkBox .van-icon-success:before {
  content: '' !important;
}

.add_audition .activeItem .van-checkbox__label {
  color: #fff;
}

</style>
<style scoped>
.add_audition {
  /* margin-bottom: .4rem; */
}
.add_audition .icon_place {
  width: 0.92rem;
}
.add_audition .form_list li:first-child {
  border-top: none;
}
.add_audition .form_list > li {
  /* border-top: .5px solid #e9e9e9; */
  border-radius: .4rem;
}

.add_audition .card {
  background: #fff;
  box-shadow:0px 0px 4px 4px rgba(234,233,233,0.5);
  overflow: hidden;
  border-radius:.266667rem;
  /* margin-bottom: .4rem; */
}
.add_audition .check_list {
  display: flex;
  align-items: center;
  /* justify-content: center; */
  flex-wrap: wrap;
  /* padding: 0 .4rem; */
  box-sizing: border-box;
}
.add_audition .check_list li {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 33.33%;
  margin-bottom: .466667rem;
}
.add_audition .salePerson{
  font-size: .293333rem;
  color: #868585;
  margin-top: .266667rem;
}

.add_audition .signIn_box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 4.6rem;
  height: .8rem;
  border-radius: .2rem;
  /* border: .5px solid rgba(255,152,83,1); */
  box-shadow:0px 0px 3px 2px rgba(235,235,235,0.5);
  margin: 0 auto;
  background: #fff;
  overflow: hidden;
}
.add_audition .signIn_box .checked_num {
  font-size: .373333rem;
  color: #FF9853;
  display: flex;
  justify-content: center;
  width: 2.6rem;
}
.add_audition .btn_signIn{
  font-size: .373333rem;
  color: #fff;
  background: #FF9F5F;
  display: inline-block;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 2rem;
}



</style>

<script>
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("addAudition");
export default {
  data() {
    return {
      jwtAuth: {},
      type: '',       // 新增 / 编辑
      dateType: '',
      searchChildrenTitle: '',
      formData: {
        schoolId: '',
        schoolName: '',
        productName: '',
        productIdList: [
        ],
        classStartTime: "",
        classEndTime: "",
        classRoomId: "",
        classRoomName: "",
        employeesId: "",
        employeesName: "",
        accommodateStudent: "",
        arrangeStudent: "",
        arrangeStudentArr: '',
      },
      arrangeStudentList: [],
      activeNames: ['1'],
      checkedList: [],
      checkedRightList: [],
      
      showBottomArea: false,
      showSearchChildren: false,
      studentList: [],
      copyStudentList: [],
      bottomAreaList: [],
      rightPopupList: [],
      bottomType: '',
      minHour: 10,
      maxHour: 20,
      minDate: new Date(),
      maxDate: new Date(2099, 10, 1),
      currentDate: new Date(),
      sexList: [
        {
          label: '男',
          id: 1
        },
        {
          label: '女',
          id: 2
        },
      ],
      schoolList: [],
      classRoomList: [],
      teacherList: [],
      productList: [],
      rightPopupType: '',
    }
  },

  beforeRouteEnter (to, from, next) {
    let type = to.params.type;
    if(type == 'add') {
      to.meta.title = '创建试听课';
      next();
    }else{
      to.meta.title = '编辑试听课';
      next();
    }
  },

  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    
    this.type = this.$route.params.type;

    console.log(this.type);
    if(this.type == 'update') {
      this.queryAuditionInfo();
    }
    
    this.queryAllSchool();
  },

  mounted() {
    console.log(this.$route)
    
  },

  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    save() {
      console.log(this.checkedList);
      let data = {};
      Object.assign(data, this.formData);

      data.studentIdList = [];

      console.log(this.checkedList);
      this.checkedList.forEach((item, index) => {
        if(item.bmStudentEmployeesList) {
          item.bmStudentEmployeesList.forEach(childrenItem => {
            let obj = {
              studentName: item.studentName,
              studentId: item.studentId,
              personName: childrenItem.employeesName,
              personId: childrenItem.employeesId,
            }
             data.studentIdList.push(obj);
          })
        }
      });

      data.arrangeStudent = this.checkedList.length.toString();

      console.log(data);
      // return false;

      this.post({
        API: 'insert',
        data: data,
      }).then(res => {
        this.$notify({ type: 'success', message: '创建成功',duration: 1000 });
        this.$router.push({
          name: 'auditionList'
        })
      })

    },
    update(type) {
      let data = {}
      Object.assign(data, this.formData);

      // data.studentIdList = this.studentList;
      // data.studentIdList.forEach(item => {
      //   // item.checkStatus = '1';
      // })

      console.log(data);
      // console.log(window.history);
      // return false;

      this.post({
        API: 'update',
        data: data,
      }).then(res => {
        this.$notify({ type: 'success', message: '编辑成功',duration: 1200 });
        if(type == 'noLink') {

        }else{
          this.$router.push({
            name: 'auditionList'
          })
        }
        
      })
    },

    queryAuditionInfo() {
      this.formGet({
        API: 'selectById',
        data: {
          id: this.$route.params.id
        }
      }).then(res => {
        this.auditionInfo = res;
        this.formData.schoolId = res.schoolId;
        this.queryAllStudent();
        this.formData = res;

        this.queryAllClassRoom();
        this.queryAllPerson();
        this.queryAllSubject();

        this.checkedList = [];
        this.formData.studentIdList.forEach(item => {
          if(item.checkStatus == 1) {
            this.checkedList.push(item.studentId);
          }
        })
        
        
      })
    },


    clcikShowBottomArea(type, dateType) {
      this.bottomType = type;

      switch (type) {
        case 'school':
          if(this.$route.params.type == 'update'){
            this.$toast.fail('校区不可编辑');
            return false;
          }
          this.showBottomArea = true;
          this.bottomAreaList = this.schoolList;
          break;
        case 'date':
          this.dateType = dateType
          this.showBottomArea = true;
          break;
        
        case 'classRoom':
          this.bottomAreaList = this.classRoomList;
          this.showBottomArea = true;
          break;
        case 'teacher':
          this.bottomAreaList = this.teacherList;
          this.showBottomArea = true;
          break;
      
        default:
          break;
      }
    },
    clcikShowRightArea(type) {
      this.rightPopupType = type;
      if(type == 'product') {
        this.searchChildrenTitle = '选择课程';
        this.rightPopupList = this.productList;
      }else if(type == 'arrangeStudentList') {
        this.searchChildrenTitle = '安排学员'
        this.rightPopupList = this.arrangeStudentList;

        this.checkedRightList = [];
        for(let i=0; i<this.arrangeStudentList.length; i++) {
          for(let k=0; k<this.studentList.length; k++) {
            if(this.arrangeStudentList[i].studentId == this.studentList[k].studentId) {
              this.checkedRightList.push(this.arrangeStudentList[i].studentId)
              break;
            }
          }
        }

        console.log(this.checkedRightList);
        console.log(this.studentList);
        


      }else{

      }
      this.showSearchChildren = true;
    },


    onConfirm(value, index) {
      console.log(`当前值：${value.id || value}, 当前索引：${index}`)
      console.log(this.bottomType)
      switch (this.bottomType) {
        case 'school':
          this.formData.schoolId = value.id;
          this.formData.schoolName = this.schoolList[index].schoolName;
          this.queryAllClassRoom();
          this.queryAllPerson();
          this.queryAllStudent();
          this.queryAllSubject();
          break;
        case 'classRoom':
          this.formData.classRoomId = value.id;
          this.formData.classRoomName = this.classRoomList[index].classRoomName;
          break;
        case 'teacher':
          this.formData.employeesId = value.id;
          this.formData.employeesName = this.teacherList[index].employeesName;
          break;
      
        default:
          break;
      }

      if(this.bottomType == 'date') {
        switch (this.dateType) {
          case 'startDate':
            this.formData.classStartTime = this.formatDate(value);
            break;
          case 'endDate':
            this.formData.classEndTime = this.formatDate(value);
            break;
          default:
            break;
        }
      }
      this.showBottomArea = false;
    },
    onCancel() {
      this.showBottomArea = false;
    },

    confirmChildPop() {
      this.showSearchChildren = false;
      
      // 课程 确认
      if(this.rightPopupType == 'product') {
        this.formData.productName = ''
        this.formData.productIdList = []
        console.log(this.checkedRightList);
        // let arr = []
        for(let i=0; i<this.checkedRightList.length; i++) {
          for(let j=0; j<this.productList.length; j++) {
            if(this.checkedRightList[i] == this.productList[j].productId) {
              let obj = {
                productId: this.productList[j].productId,
                productName: this.productList[j].productName,
              }
              this.formData.productIdList.push(obj);
              this.formData.productName += this.productList[j].productName + '，'
            }
          }
        }
      } 
      
      // 安排学员 确认
      if (this.rightPopupType == 'arrangeStudentList') {
        
        // this.studentList = this.copyStudentList.concat();
        let arr = [];
        
        for(let i=0; i<this.arrangeStudentList.length; i++) {
          for(let k=0; k<this.checkedRightList.length; k++) {
            if(this.checkedRightList[k] == this.arrangeStudentList[i].studentId) {
              // this.arrangeStudentList[i].checkStatus = 0;
              for(let j=0; j<this.checkedList.length; j++) {
                if(this.arrangeStudentList[i].studentId == this.checkedList[j]) {
                  this.arrangeStudentList[i].checkStatus = '1';
                  break;
                }else{
                  this.arrangeStudentList[i].checkStatus = '0';
                }
              }
              this.arrangeStudentList[i].auditionMid = this.auditionInfo.auditionMid;
              arr.push(this.arrangeStudentList[i]);
              break;
            }
          }
        };
        
        this.studentList = arr;
        this.formData.studentIdList = this.studentList;

        console.log(this.checkedList);
        console.log(this.checkedRightList);
        console.log(this.studentList)
        console.log(this.copyStudentList)
        console.log(this.arrangeStudentList);
        console.log(this.formData);


        // return false;
        this.update('noLink');
      }
      
    },

    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },

    formatDate(date) {
      let month = (date.getMonth()+1) > 9 ? (date.getMonth()+1) : "0" + (date.getMonth()+1);
      let day = (date.getDate()) > 9 ? (date.getDate()) : "0" + (date.getDate());
      let hours = (date.getHours()) > 9 ? (date.getHours()) : "0" + (date.getHours());
      let minutes = (date.getMinutes()) > 9 ? (date.getMinutes()) : "0" + (date.getMinutes());
      let seconds = (date.getSeconds()) > 9 ? (date.getSeconds()) : "0" + (date.getSeconds());

      let dateString =
          date.getFullYear() + "-" +
          month + "-" +
          day + " " +
          hours + ":" +
          minutes
          
      return dateString; 
    },




    updateCheckStatus() {
      let data = {
        bmAuditionStudents: [],
      };

      let studentList = this.formData.studentIdList

      for(let i=0; i<this.checkedList.length; i++) {
        for(let j=0; j<studentList.length; j++) {
          if(this.checkedList[i] == studentList[j].studentId) {
            let obj = {
              auditionMid: studentList[j].auditionMid,
              studentId: studentList[j].studentId,
              checkStatus: '1',
            }
            data.bmAuditionStudents.push(obj);
          }
        }
      }
      
      console.log(data)
      // return false;

      this.post({
        API: 'updateCheckStatus',
        data: data
      }).then(res => {
        this.$notify({ type: 'success', message: '签到成功',duration: 1200 });
      })
    },

    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      
      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || 'studentManagement',
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        res = res.filter(val => {
          return val.schoolId !== '';
        });
        res.map((val) => {
          val.label = val.schoolName;
          val.id = val.schoolId;
        })

        if(btnId) {
          this.powerSchoolList = res
        }else{
          this.schoolList = res
        }
      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    queryAllClassRoom() {
      this.formGet({
        API: 'queryClassRoomBySchool',
        data: {
          schoolId: this.formData.schoolId
        }
      }).then(res => {
        res.map((val) => {
          val.label = val.classRoomName;
          val.id = val.classRoomId;
        })
        this.classRoomList = res;
      })
    },
    // 教师
    queryAllPerson() {
      this.post({
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: [9],
          schoolId: this.formData.schoolId,
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.employeesId;
          val.label = val.employeesName;
        })
        this.teacherList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })

    },
    queryAllStudent() {
      this.post({
        API: 'queryStudentForAudition',
        data: {
          schoolId: [this.formData.schoolId],
          positionCode: '5',
        }
      }).then(res => {
        console.log(this.type)
        if(this.type == 'add') {
          this.studentList = res;
        }else{
          this.studentList = this.formData.studentIdList
          this.copyStudentList = this.formData.studentIdList
          res.map((val) => {
            val.id = val.studentId;
            val.label = val.studentName;
          })
          this.arrangeStudentList = res;
          // console.log(this.studentList)
        }
      })
    },
    queryAllSubject() {
      let data = {
        schoolId: this.formData.schoolId,
      }
      this.formGet({
        API: 'queryProductBySchool',
        data: data
      }).then(res => {
        res.map((val) => {
          val.id = val.productId;
          val.label = val.productName;
        })
        this.productList = res;
        // this.rightPopupList = res;

        if(this.type == 'update') {
          this.checkedRightList = [];
          this.formData.productIdList.forEach(item => {
            this.checkedRightList.push(item.productId);
          })

          this.formData.productName = '';
          for(let i=0; i<this.checkedRightList.length; i++) {
            for(let j=0; j<this.productList.length; j++) {
              if(this.checkedRightList[i] == this.productList[j].productId) {
                this.formData.productName += this.productList[j].productName + '，'
              }
            }
          }

          console.log(this.checkedRightList)
        }
      }).catch(err => {
        this.$toast.fail(err);
      })
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`
      }else if (type === 'day') {
        return `${value}日`
      }else if (type === 'hour') {
        return `${value}点`
      }else if (type === 'minute') {
        return `${value}分`
      }
      return value;
    }
  },

  computed: {
    computedCheckStudent() {
      return function(item) {
        if(this.$route.params.type == 'add') {
          return item
        }else{
          return item.studentId
        }
      }
    },
    computedTitle() {
      if(this.type == 'add') {
        return '安排学员'
      }else{
        return '学员签到'
      }
    }
  }
}
</script>